<template>
  <div class="app-container">
    <!-- 操作区-->
    <div class="filter-container">
      <div class="searchform">
        <el-form ref="searchForm" :model="search" label-width="90px" size="mini" label-position="right">
          <el-row :gutter="6">
            <el-col :xs="24" :sm="8" :md="6">
              <el-form-item prop="roleCode" label="岗位代码">
                <el-input v-model="search.roleCode" placeholder="岗位代码" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="6">
              <el-form-item prop="roleName" label="岗位名称">
                <el-input v-model="search.roleName" placeholder="岗位名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8" :md="6">
              <el-form-item prop="dataType" label="岗位类型">
                <r-select v-model="search.dataType" type="4508" placeholder="岗位类型" clearable />
              </el-form-item>
            </el-col>
            <div style="text-align:right">
              <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置</el-button>
            </div>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 用户列表 -->
    <div class="table">
      <div class="tableHead">
        <div class="tabletitle">岗位信息</div>
        <div class="btnGroup">
          <el-button-group>
            <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          </el-button-group>
        </div>
      </div>
      <BaseTable v-loading="loading" ref="table" @chaneg-size="changeSizeHandle" @chaneg-page="changePageHandle">
        <el-table-column label="序号" type="index" min-width="40px"/>
        <el-table-column align="center" label="操作" min-width="50px">
          <template slot-scope="scope">
            <el-tooltip class="item" content="APP权限" placement="bottom">
              <el-button type="text" style="font-size: 20px;" icon="el-icon-mobile-phone" @click="appPermission(scope.row)"/>
            </el-tooltip>
            <el-tooltip class="item" content="权限" placement="bottom">
              <el-button :disabled="scope.row.ROLE_CODE==='SYSADMIN'" type="text" style="font-size: 20px;" icon="el-icon-check" @click="permission(scope.row.ROLE_ID, scope.row.DATA_TYPE)"/>
            </el-tooltip>
            <el-tooltip class="item" content="删除" placement="bottom">
              <el-popover v-model="scope.row.visible" placement="top" width="160">
                <p>确定删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
                  <el-button type="primary" size="mini" @click="scope.row.visible = false;del(scope.row)">确定</el-button>
                </div>
                <el-button slot="reference" :disabled="scope.row.ROLE_CODE==='SYSADMIN'" type="text" style="font-size: 20px;" icon="el-icon-delete" @click="scope.row.visible = true"/>
              </el-popover>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="ROLE_CODE" label="岗位代码" min-width="50px"/>
        <el-table-column prop="ROLE_NAME" label="岗位名" min-width="50px"/>
        <el-table-column :formatter="filterCode" prop="DATA_SOURCE" label="数据来源" min-width="50px" type="1046"/>
        <el-table-column :formatter="filterCode" prop="DATA_TYPE" label="岗位类型" min-width="50px" type="4508"/>
      </BaseTable>
    </div>
    <!-- 弹框 -->
    <el-dialog v-dialogDrag ref="roleDialog" :visible.sync="dialogVisible" :close-on-click-modal="false" title="岗位信息新增" width="25%">
      <!-- 查询条件 -->
      <div class="elform">
        <el-form ref="roleSearchForm" :model="form" :rules="rules" size="mini" label-width="90px">
          <el-row :gutter="6">
            <el-col :xs="24" :sm="24" :md="24">
              <el-form-item prop="roleCode" label="岗位代码">
                <el-input v-model="form.roleCode" placeholder="岗位代码" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24">
              <el-form-item prop="roleName" label="岗位名称">
                <el-input v-model="form.roleName" placeholder="岗位名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24">
              <el-form-item prop="dataType" label="岗位类型">
                <r-select v-model="form.dataType" type="4508" placeholder="岗位类型" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <!-- <span slot="footer" class="dialog-footer"> -->
        <el-button type="primary" @click="req">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>

        <!-- </span> -->
      </div>

    </el-dialog>
    <!-- 弹框 -->
    <el-dialog
      v-dialogDrag
      ref="authDialog"
      :visible.sync="dialogVisibleAuth"
      :close-on-click-modal="false"
      :before-close="clear"
      title="分配权限"
      top="5vh"
      width="70%">
      <el-row style="display:flex;flex-direction: column">
        <el-row style="height: 495px">
          <div class="menu-header">菜单权限</div>
          <el-scrollbar style="height: 450px;border: 1px solid rgba(144,147,153,.5);">
            <el-col style="padding: 5px 3px;">
              <el-tree
                v-loading="loading"
                ref="tree"
                :data="jsonTree"
                :expand-on-click-node="false"
                style="margin-top: 12px;"
                show-checkbox
                node-key="id"
                highlight-current
                @node-click="nodeClickHandle" />
            </el-col>
          </el-scrollbar>
        </el-row>
        <el-row style="text-align: center;margin-bottom: 15px;">
          <el-button type="primary" @click="reqAuth">确 定</el-button>
          <el-button @click="clear()">取 消</el-button>
        </el-row>
      </el-row>
    </el-dialog>
    <appRoleManage v-if="appVisible" :visible.sync="appVisible" :data-type="10461001" :menu-category="menuCategory" :id="appRoleId"/>
  </div>
</template>

<script>
import {
  getJsonTree
} from '@/api/admin/utils/index'
import appRoleManage from './appRoleManage'
import {
  getRoleList,
  getMenu,
  roleData,
  getRoleMenuRange,
  getRoleMenuAction,
  setRoleAuth,
  addRole,
  deleteRole
} from '@/api/admin/auth/roleManage'
import BaseTable from '@/components/BaseTable'
import formMixins from '@/mixins/formMixins'
import rSelect from '@/components/Select/Select'
import _ from 'lodash'
import {
  systemCode
} from '@/utils/validator'
export default {
  name: 'RoleManage',
  components: {
    BaseTable,
    rSelect,
    appRoleManage
  },
  mixins: [formMixins],
  data() {
    const validatePositionCode = (rule, value, callback) => {
      if (value === undefined || value === '' || value === null) {
        callback(new Error('请输入岗位代码'))
      } else {
        systemCode(rule, value, callback)
      }
    }
    return {
      appVisible: false,
      appRoleId: '',
      menuCategory: 0,
      // 查询条件
      search: {
        pageNum: 1,
        limit: 10,
        roleCode: '',
        roleName: '',
        dataSource: 10461001,
        dataType: '',
        isDealer: 'true'
      },
      menuId: '',
      checkListRoleMenuRange: [],
      checkListRoleMenuAction: [],
      dialogVisible: false,
      dialogVisibleAuth: false,
      loading: false,
      rangeloading: false,
      actionloading: false,
      authloading: false,
      roleloading: false,
      roleId: '',
      dataType: '',
      table: {},
      objRange: [],
      objAction: [],
      roleMenuAction: [],
      roleMenuRange: [],
      reList: [],
      form: {},
      tree: [],
      rules: {
        roleName: [{
          required: true,
          message: '请填写岗位名称',
          trigger: 'blur'
        }],
        roleCode: [{
          required: true,
          validator: validatePositionCode,
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    jsonTree() {
      this.tree.forEach(el => (el.label = el.text))
      this.tree.forEach(el => (el.parentId = el.parent))
      return getJsonTree(this.tree)
    }
  },
  mounted() {
    this.searchHandle()
  },
  methods: {
    // 加载树
    searchTree() {
      this.loading = true
      const param = {
        roleId: this.roleId,
        dataType: this.dataType
      }
      getMenu(param)
        .then(res => {
          this.loading = false
          this.deleteRes(res.treejson)
          this.tree = res.treejson
          console.log(res.treejson)
        })
        .catch(err => {
          this.loading = false
        })
    },
    // 删除无效数据(无父节点)
    deleteRes(res) {
      const result = []
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        const pid = res[i].parent
        const oid = res[i].id
        result[oid] = pid
      }
      for (let j = 0; j < res.length; j++) {
        // 一级父节点跳过
        if (res[j].parent === '#') continue
        if (res[j] && result[res[j].parent] === null) {
          const index = j
          j = 0
          delete result[res[index].id]
          res.splice(index, 1)
        }
      }
    },
    // 查询
    searchHandle() {
      this.loading = true
      const table = this.$refs['table']
      getRoleList(this.search)
        .then(res => {
          table.complete().filData(res)
          this.loading = false
        })
        .catch(err => {
          table.complete()
          this.loading = false
        })
    },
    // 新增
    add() {
      this.dialogVisible = true
      this.form = {}
      this.$nextTick(() => {
        this.$refs.roleSearchForm.clearValidate()
      })
    },
    // 删除
    del(data) {
      const id = data.ROLE_ID
      deleteRole(id).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.searchHandle()
      })
        .catch(err => {
        })
    },
    // 树点击
    nodeClickHandle(data) {
      const {
        // id,
        text
      } = data
      this.text = text
      // this.searchMenuHandle(id)
    },
    // 显示客户信息操作权限
    searchMenuHandle(id) {
      this.rangeloading = true
      this.actionloading = true
      this.menuId = id
      getRoleMenuRange(id, this.roleId)
        .then(res => {
          this.rangeloading = false
          this.objRange = _.cloneDeep(res)
          this.roleMenuRange = []
          if (this.checkListRoleMenuRange != null) {
            for (let i = 0; i < this.checkListRoleMenuRange.length; i++) {
              if (id === this.checkListRoleMenuRange[i].split('-')[0]) {
                const rangArray = this.checkListRoleMenuRange[i].split('-')[1].split(',')
                for (let j = 0; j < rangArray.length; j++) {
                  this.roleMenuRange.push(Number(rangArray[j]))
                }
                return
              }
            }
          }
        })
        .catch(err => {
          this.rangeloading = false
        })
      getRoleMenuAction(id, this.roleId)
        .then(res => {
          this.actionloading = false
          console.log(res)
          this.objAction = _.cloneDeep(res)
          this.roleMenuAction = []
          if (this.checkListRoleMenuAction != null) {
            for (let i = 0; i < this.checkListRoleMenuAction.length; i++) {
              if (id === this.checkListRoleMenuAction[i].split('-')[0]) {
                const actionArray = this.checkListRoleMenuAction[i].split('-')[1].split(',')
                for (let j = 0; j < actionArray.length; j++) {
                  this.roleMenuAction.push(Number(actionArray[j]))
                }
                return
              }
            }
          }
        })
        .catch(err => {
          this.actionloading = false
        })
    },
    // 分配权限展示打开窗口
    permission(roleId, dataType) {
      this.dialogVisibleAuth = true
      this.roleId = roleId
      this.dataType = dataType
      this.searchTree()
      /* getMaintain().then(res => {
          this.$refs.Todo.sitesRepairRepair = _.cloneDeep(res)
        }).catch(err => {})
        getAccessories().then(res => {
          this.$refs.part.sitesPartPart = _.cloneDeep(res)
        }).catch(err => {})
        getVehicleWarehouse().then(res => {
          this.$refs.storageVec.sitesVec = _.cloneDeep(res)
        }).catch(err => {})
        getDiscountMode().then(res => {
          this.$refs.favorableModels.sitesDiscountMode = _.cloneDeep(res)
        }).catch(err => {})
        getPartAccessories().then(res => {
          this.$refs.storagePart.sitesPart = _.cloneDeep(res)
        }).catch(err => {})
        getJpckAccessories().then(res => {
          this.$refs.storageJpck.sitesJpck = _.cloneDeep(res)
        }).catch(err => {})*/
      roleData(roleId, dataType).then(res => {
        const restreejson = res.treejson
        /**
           * 勾选菜单
           */
        const selectedmenu = []
        for (let j = 0; j < restreejson.length; j++) {
          const states = restreejson[j].state
          if (states.checked === true) {
            selectedmenu.push(restreejson[j].id)
          }
        }
        this.$refs['tree'].setCheckedKeys(selectedmenu)
        // 操作权限操作按钮
        this.checkListRoleMenuRange = res.treeMenuRange
        this.checkListRoleMenuAction = res.treeMenuAction
      })
    },
    cancel() {
      this.dialogVisible = false
    },
    // 新增保存
    req() {
      this.$refs['roleSearchForm'].validate((valid) => {
        if (valid) {
          // this.$set(this.form, 'dataType', '10461001')
          this.$set(this.form, 'dataSource', '10461001')
          addRole(this.form)
            .then(() => {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              // this.clear();
              this.dialogVisible = false
              this.searchHandle()
            })
            .catch(err => {
              // this.$message({
              //   type: "error",
              //   message: err.response.data.errorMsg
              // });

            })
        }
      })
    },
    // 分配权限保存
    reqAuth() {
      const selectedHalfNode = this.$refs['tree'].getCheckedKeys() // 父节点
      const selectedNode = this.$refs['tree'].getHalfCheckedKeys() // 子节点
      const allNode = selectedHalfNode.concat(selectedNode)
      if (allNode === '') {
        this.$message({
          type: 'info',
          message: '请至少分配一条权限!'
        })
      } else {
        // 去掉一级菜单
        for (var k = 0; k < allNode.length; k++) {
          var nodekv = allNode[k]
          if (nodekv.length === 2) {
            allNode.splice(k, 1)
          }
        }
        const params = {
          roleId: this.roleId,
          nowTree: allNode.join(','),
          treeMenuRange: this.checkListRoleMenuRange.join(';'),
          treeMenuAction: this.checkListRoleMenuAction.join(';'),
          nowRole: this.roleId
        }
        this.$refs['tree'].setCheckedKeys(selectedHalfNode)
        setRoleAuth(this.roleId, params)
          .then(res => {
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            this.clear()
          })
          .catch(err => {
            // this.$message({
            //   type: "error",
            //   message: err.response.data.errorMsg
            // });

          })
      }
    },
    // 返回清空列表
    clear() {
      this.dialogVisible = false
      this.dialogVisibleAuth = false
      this.form = {}
      this.search.roleCode = ''
      this.search.roleName = ''
      this.objAction = []
      this.objRange = []
      this.$refs['tree'].setCheckedKeys(this.reList)
      this.searchHandle()
    },
    // 操作权限改变事件
    handleRoleMenuRangeChange(value) {
      if (this.checkListRoleMenuRange != null && this.checkListRoleMenuRange.length > 0) {
        let ok = true
        for (let i = 0; i < this.checkListRoleMenuRange.length; i++) {
          if (this.menuId === this.checkListRoleMenuRange[i].split('-')[0]) {
            if (value.length === 0) {
              this.checkListRoleMenuRange.splice(i, 1)
            } else {
              this.checkListRoleMenuRange[i] = this.menuId + '-' + value.join(',')
            }
            ok = false
            return
          }
        }
        if (ok) {
          this.checkListRoleMenuRange.push(this.menuId + '-' + value.join(','))
        }
      } else {
        this.checkListRoleMenuRange = []
        this.checkListRoleMenuRange.push(this.menuId + '-' + value.join(','))
      }
    },
    // 操作按钮改变事件
    handleRoleMenuActionChange(value) {
      if (this.checkListRoleMenuAction != null && this.checkListRoleMenuAction.length > 0) {
        let ok = true
        for (let i = 0; i < this.checkListRoleMenuAction.length; i++) {
          if (this.menuId === this.checkListRoleMenuAction[i].split('-')[0]) {
            if (value.length === 0) {
              this.checkListRoleMenuAction.splice(i, 1)
            } else {
              this.checkListRoleMenuAction[i] = this.menuId + '-' + value.join(',')
            }
            ok = false
            return
          }
        }
        if (ok) {
          this.checkListRoleMenuAction.push(this.menuId + '-' + value.join(','))
        }
      } else {
        this.checkListRoleMenuAction = []
        this.checkListRoleMenuAction.push(this.menuId + '-' + value.join(','))
      }
    },
    appPermission(row) {
      this.appVisible = true
      this.appRoleId = row.ROLE_ID
      this.menuCategory = row.DATA_TYPE
    }
  }

}

</script>

<style scoped>
  .el-checkbox+.el-checkbox {
    margin-left: 0px;
  }

  .el-checkbox {
    margin-right: 25px;
  }

  .menu-header {
    height: 30px;
    line-height: 30px;
    margin-bottom: 5px;
    background: #eee;
    text-indent: 5px;
  }

  .app-container>>>.el-dialog__body {
    padding: 0 20px;
  }

</style>
